package com.shenyaocn.android.demoUartSDK;

import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.shenyaocn.android.UartSDK.UartClient;
import com.shenyaocn.android.UartSDK.usb.DeviceFilter;
import com.shenyaocn.android.UartSDK.usb.USBMonitor;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private UartClient uartClient;
    //
    // UartClient 函数
    //
    // 发送数传数据 putPayload(DataType type, byte[] payload);
    // type 发送数据的通道，参考 DataType 类型
    // playload 发送的数据，长度不限，SDK自动分包
    //
    //
    //
    //
    // 打开 boolean VideoClient.openUsbSerial(UsbDevice device)
    // device 已经获得权限的 Usb串口设备 参照以下示例代码操作
    // 返回值，成功 true 失败 false
    //
    //
    // 关闭/停止 VideoClient.stopClient
    //
    // 参考下列代码获取数据

    private USBMonitor mUSBMonitor;
    private UsbDevice uartDevice;
    private Spinner spinner;
    private ScrollView scrollView;
    private TextView tv_content;
    private TextView tv_send_count;
    private StringBuilder sb = new StringBuilder();
    private TextView tv_count;
    private RadioGroup radioGroup;
    private EditText et_send;
    private boolean hex = true;
    private int  passageway = 1;
    private UartClient.DataType dataType;

    //使用 USBMonitor 处理USB连接回调
    private final USBMonitor.OnDeviceConnectListener mOnDeviceConnectListener = new USBMonitor.OnDeviceConnectListener() {

        // USB设备插入
        @Override
        public void onAttach(final UsbDevice device) {

            if(deviceHasConnected(device) || uartDevice != null)
                return;

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (device == null) {
                            final List<UsbDevice> devices = mUSBMonitor.getDeviceList();
                            if (devices.size() == 1) {
                                mUSBMonitor.requestPermission(devices.get(0));
                            }
                        } else {
                            mUSBMonitor.requestPermission(device);
                        }
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
        }

        // USB设备物理断开
        @Override
        public void onDettach(UsbDevice device) {
            if(!deviceIsUartVideoDevice(device)) {
                return;
            }

            if(!deviceHasConnected(device)) {
                return;
            }

            disconnected();
        }

        // USB设备获得权限
        @Override
        public void onConnect(UsbDevice device, USBMonitor.UsbControlBlock ctrlBlock, boolean createNew) {
            if(!deviceIsUartVideoDevice(device)) {
                return;
            }
            if(deviceHasConnected(device)) {
                return;
            }

            synchronized (this) {
                if(deviceIsUartVideoDevice(device)) {
                    if(uartClient.openUsbSerial(device))
                        uartDevice = device;
                }
            }
        }

        // USB设备关闭连接
        @Override
        public void onDisconnect(UsbDevice device, USBMonitor.UsbControlBlock ctrlBlock) {
            if(!deviceIsUartVideoDevice(device)) {
                return;
            }

            if(!deviceHasConnected(device)) {
                return;
            }

            disconnected();
        }

        // USB设备权限获取失败
        @Override
        public void onCancel() {

        }
    };


    private boolean deviceHasConnected(UsbDevice device) {
        return device != null && device.equals(uartDevice);
    }

    private static boolean deviceIsUartVideoDevice(UsbDevice device) { // 图传使用的USB id
        return device != null && (device.getVendorId() == 4292 && device.getProductId() == 60000);
    }

    // 处理设备断开或手段断开 还可以在此加入其它需要释放的操作
    private synchronized void disconnected() {
        uartClient.stopClient();
        uartDevice = null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        uartClient = new UartClient(this); // 初始化UartClient

        uartClient.setClientListener(new UartClient.ClientListener() { // 设置回调，获取数据

            @Override
            public void onReceived(UartClient.DataType type, byte[] bytes) {
                // type 对应DataType通道类型
                // data 接收到的数据

                switch (type){
                    case A1:
                        if(passageway == 4){
                            count += bytes.length;
                            print(bytes);
                        }
                        break;
                    case A3:
                        if(passageway == 3){
                            count += bytes.length;
                            print(bytes);
                        }
                        break;

                    case A5:
                        if(passageway == 1){
                            count += bytes.length;
                            print(bytes);
                        }
                        break;
                    case A7:
                        // GPS data callback
                        if(passageway == 2){
                            count += bytes.length;
                            print(bytes);
                        }
                        break;
                }

            }

            @Override
            public void onError(String error) {
                // 错误回调
            }
        });


        mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);
        final List<DeviceFilter> filters = DeviceFilter.getDeviceFilters(this, R.xml.device_filter);
        mUSBMonitor.setDeviceFilter(filters);
        mUSBMonitor.register();
        // USBMonitor 监听 device_filter.xml指定的USB设备插拔

        tv_content = findViewById(R.id.tv_content);
        tv_send_count = findViewById(R.id.tv_send_count);
        tv_count = findViewById(R.id.tv_count);
        scrollView = findViewById(R.id.scrollView);
        spinner = findViewById(R.id.spacer);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        passageway = 1;
                        dataType = UartClient.DataType.A5;
                        break;
                    case 1:
                        passageway = 2;
                        dataType = UartClient.DataType.A7;
                        break;
                    case 2:
                        passageway = 3;
                        dataType = UartClient.DataType.A3;
                        break;
                    case 3:
                        passageway = 4;
                        dataType = UartClient.DataType.A1;
                        break;
                    default:
                        dataType = UartClient.DataType.A3;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spinner.setSelection(0);
        dataType = UartClient.DataType.A5;
        radioGroup = findViewById(R.id.radioGroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.rt_hex:
                        hex = true;
                        break;
                    case R.id.rt_text:
                        hex = false;
                        break;
                }
            }
        });

        et_send = findViewById(R.id.et_send);
        findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                byte[] bytes = et_send.getText().toString().trim().getBytes();
                sendCount += bytes.length;
                tv_send_count.setText("发送：" + sendCount);
                uartClient.putPayload(dataType,bytes);
            }
        });
        findViewById(R.id.btn_clean).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sb = new StringBuilder();
                tv_content.setText("");
            }
        });
        findViewById(R.id.btn_reset_count).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count = 0;
                tv_count.setText("收到：" + count);
            }
        });
        findViewById(R.id.btn_reset_send_count).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCount = 0;
                tv_send_count.setText("发送：" + sendCount);
            }
        });
    }

    private int count = 0;
    private int sendCount = 0;

    private void print(final byte[] bytes){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(sb.length() > 50 * 1024){
                    sb = new StringBuilder();
                }
                if(hex){
                    sb.append(bytesToHex(bytes));
                    tv_content.setText(sb.toString());
                }else {
                    sb.append(new String(bytes));
                    tv_content.setText(sb.toString());
                }
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                tv_count.setText("收到：" + count);
            }
        });


    }


    public  String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString().toUpperCase();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        disconnected();

        if (mUSBMonitor != null) {
            mUSBMonitor.unregister();
            mUSBMonitor.destroy();
            mUSBMonitor = null;
        }
    }
}
